package com.zwb.consumer;

import com.rabbitmq.client.Channel;
import com.zwb.email.EmailSendUtil;
import com.zwb.service.common.MailConstants;
import com.zwb.service.pojo.Employee;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * @author 头发又黑又长
 * @Date 2022/9/9 10:06
 * @email zwb15083976291@163.com
 */
@Slf4j
@Component
public class MailReceiver {

    @Autowired
    private EmailSendUtil emailSendUtil;

    @Autowired
    private RedisTemplate redisTemplate;


    @RabbitListener(queues = MailConstants.DELAY_QUEUE, containerFactory = "simpleRabbitListenerContainerFactory")
    public void handle(Employee employee, Message message, Channel channel) {
        /* 消息序号*/
        long deliveryTag = message.getMessageProperties().getDeliveryTag();
        HashOperations hashOperations = redisTemplate.opsForHash();
        /* 消息id */
        String msgId = (String) message.getMessageProperties().getHeader("spring_returned_message_correlation");


        try {
            /* 查询redis 中是否存在相同需要的msgID */
            if (hashOperations.entries("mail_log").containsKey(msgId)) {
                log.info("消息已经被消费=================================>{}", msgId);
                channel.basicNack(deliveryTag, false, false);
                return;
            }
            emailSendUtil.emailSend("入职欢迎邮件", employee, "mail");
            log.info("正在给{} 发送入职邮件", employee.getName());
            /* 保存到redis中 */
            hashOperations.put("mail_log", msgId, "ok");
            /* 手动确认 */
            channel.basicAck(deliveryTag, false);
        } catch (Exception e) {
            log.error("邮件发送失败===================>>：{}", e.getMessage());
            try {
                channel.basicNack(deliveryTag, false, false);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }

    }
}
